﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Alma.Models;
using AlmaDatabase;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;

namespace AlmaLite.Controllers
{
    public class MobileController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            if (Session["UserId"] != null)
                return RedirectToAction("Profile", "Mobile");
            return View();
        }

        public ActionResult Profile()
        {
            CartModel newComp = new CartModel();
            if (Session["UserId"] == null)
                return RedirectToAction("Authenticate");
            using (var context = new AlmaDBEntities())
            {
                var list = from product in context.Products
                           join jproduct in context.Cart on product.ID equals jproduct.ID_Product
                           orderby product.ID_Shop
                           select product;
                foreach (var pro in list)
                {
                    ProductDetailsModel productModel = new ProductDetailsModel(pro);
                    var cartProd = from cart in context.Cart
                                   where cart.ID_Product == pro.ID
                                   select cart;
                    productModel.Quantity = cartProd.First().Quantity;
                    newComp.productList.Add(productModel);
                }


                /*lists*/
                long usrID = (long)Session["UserID"];
                var lists = from usrlist in context.T_List
                            where usrlist.ID_User == usrID
                            select usrlist;
                List<string> dropList = new List<string>();
                foreach (var ulist in lists)
                {
                    dropList.Add(ulist.List_Name);
                    newComp.publicLists.Add(new ListModel(ulist.ID_List, ulist.ID_User, ulist.List_Name));
                }
                ViewData["drop_list"] = new SelectList(dropList);

            }
            ViewBag.Cart = newComp;
            return View();
        }

        public ActionResult ShowList(int id)
        {
            ListModel newComp = new ListModel();
            newComp.ID = id;
            if (Session["UserId"] == null)
                return RedirectToAction("Connect", "User");
            using (var context = new AlmaDBEntities())
            {
                /*product*/
                var list = from product in context.Products
                           join jproduct in context.J_List_Products on product.ID equals jproduct.ID_Product
                           where jproduct.ID_List == id
                           select product;
                foreach (var pro in list)
                {
                    ProductDetailsModel productModel = new ProductDetailsModel(pro);
                    var listProd = from cart in context.J_List_Products
                                   where cart.ID_Product == pro.ID
                                   select cart;
                    productModel.Quantity = listProd.First().Quantity;
                    newComp.productList.Add(productModel);
                }
                var list2 = from lists in context.T_List
                            where lists.ID_List == id
                            select lists;
                newComp.List_Name = list2.First().List_Name;
            }
            ViewBag.List = newComp;
            return View();
        }

        public ActionResult ShowShop(int id)
        {
            ShopModel shopModel = new ShopModel();
            using (var entities = new AlmaDBEntities())
            {
                var shop = (from p in entities.Shops where p.ID == id select p).First();
                shopModel.ID = id;
                shopModel.ID_User = shop.ID_User;
                shopModel.Name = shop.Name;
                shopModel.Email = shop.Email;
                shopModel.Phone = shop.Phone;
                shopModel.Fax = shop.Fax;
                shopModel.Address = shop.Address;
                shopModel.Zipcode = shop.Zipcode;
                shopModel.Town = shop.Town;
                shopModel.Country = shop.Country;
                shopModel.Description = shop.Description;
                shopModel.LocationX = shop.LocationX;
                shopModel.LocationY = shop.LocationY;
                shopModel.ImgUrl = shop.ImgUrl;

                shopModel.Products = new List<ProductDetailsModel>();
                foreach (ProductDetailsModel pro in
                    (from p in entities.Products where p.ID_Shop == id select p).Select(
                                                                                         product =>
                                                                                         new ProductDetailsModel
                                                                                         {
                                                                                             Name = product.Name,
                                                                                             ID = product.ID,
                                                                                             ImgUrl =
                                                                                                 product.ImgUrl ??
                                                                                                 "~/Content/images/unavailable.gif"
                                                                                         }))
                {
                    shopModel.Products.Add(pro);
                }
               
            }
            List<int> list = new List<int>();
            for (int i = 1; i < 6; i++)
                list.Add(i);
            ViewData["drop"] = new SelectList(list);

            ViewBag.Shop = shopModel;

            return View();
        }

        private static readonly OpenIdRelyingParty m_openId = new OpenIdRelyingParty();

        private static readonly Dictionary<string, string> m_openidIdentities = new Dictionary<string, string>
                                                                                    {
                                                                                        {
                                                                                            "google",
                                                                                            @"https://www.google.com/accounts/o8/id"
                                                                                            },
                                                                                        {
                                                                                            "yahoo",
                                                                                            @"http://me.yahoo.com "
                                                                                            },
                                                                                        {
                                                                                            "myopenid",
                                                                                            @": http://www.myopenid.com"
                                                                                            }
                                                                                    };
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
        /*
        public ActionResult Connect()
        {
            //Display Login form
            Session["loginBackUrl"] = Request.UrlReferrer.AbsoluteUri;

            return View("Connect");
        }


        public PartialViewResult ChangeOpenIdProvider(string provider)
        {
            return PartialView("_OpenIdProvider", provider);
            //return Content(provider);
        }
        */
        [ValidateInput(false)]
        public ActionResult Authenticate()
        {
            var response = m_openId.GetResponse();
            if (response == null)
            {
                //Identifier submit
                string provider = "google";
                if (!m_openidIdentities.ContainsKey(provider))
                {
                    ViewBag.Message = "Provider inconnu";
                    return View("Index");
                }
                string openidIdentifier = m_openidIdentities[provider];
                Identifier id;
                if (Identifier.TryParse(openidIdentifier, out id))
                {
                    try
                    {
                        var request = m_openId.CreateRequest(openidIdentifier);
                        request.AddExtension(new ClaimsRequest
                        {
                            Nickname = DemandLevel.Require,
                            Email = DemandLevel.Require,
                            FullName = DemandLevel.Require,
                            Country = DemandLevel.Require,
                            Language = DemandLevel.Require,
                            BirthDate = DemandLevel.Require,
                            Gender = DemandLevel.Require,
                            TimeZone = DemandLevel.Require,
                        });
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException)
                    {
                        ViewBag.Message = "Could not connect to OpenId Provider " + openidIdentifier + ".";
                        return View("Index");
                    }
                }
                else
                {
                    //Provider sending response
                    ViewBag.Message = "Invalid identifier";
                    return View("Index");
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        var extensions = response.UnifyExtensionsAsSreg(true);
                        //Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                        using (var context = new AlmaDBEntities())
                        {
                            string identifier = response.ClaimedIdentifier.ToString();
                            var request = from users in context.Users
                                          where users.OpenId != null && users.OpenId == identifier
                                          select users;
                            User user = request.FirstOrDefault();
                            
                            if (user == null)
                            {
                                ViewBag.Message = "Vous devez d'abord vous connecter au site web classique pour créer un compte.";
                                return View("Index"); 
                                /*
                                user = new User()
                                {
                                    Email = extensions.Email,
                                    IsAdmin = 0,
                                    OpenId = identifier
                                };
                                //context.Users.AddObject (user);
                                //context.SaveChanges ();
                                //Session["UserId"] = user.ID;
                                return RedirectToAction("Create",
                                                         new RouteValueDictionary(
                                                             new { controller = "User", action = "Create", openId = identifier, email = extensions.Email }));
                                //return this.RedirectToAction ("Create", "User", new { id = new EmptyUser (user)}); */
                            }
                            
                            Session["UserId"] = user.ID;
                            FormsAuthentication.SetAuthCookie(user.OpenId, false);
                        }
                        return RedirectToAction("Profile", "Mobile");
                    case AuthenticationStatus.Canceled:
                        ViewBag.Message = "Canceled at provider";
                        return View("Index");
                    case AuthenticationStatus.Failed:
                        ViewBag.Message = response.Exception.Message;
                        return View("Index");
                }
            }
            return RedirectToAction("Index");
        }


    }
}
